/**Copyright 2002-2012 the original author or authors.**Licensed under the Apache License,Version 2.0(the"License");*you may not use this file except in compliance with the License.*You may obtain a copy of the License at**http://www.apache.org/licenses/LICENSE-2.0
**Unless required by applicable law or agreed to in writing,software*distributed under the License is distributed on an"AS IS"BASIS,*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.*See the License for the specific language governing permissions and*limitations under the License.*/

package com.boot2.core.web;

import com.boot2.core.utils.AesUtil;
import com.boot2.core.utils.StringUtils;
import lombok.extern.apachecommons.CommonsLog;

import java.beans.PropertyEditorSupport;
import java.util.Set;

/**
 * 
 * @ClassName: DecipherLongIdEditor
 * @description: 参数解密，此参数包括问号后面的健值对参数和@PathVarient的参数
 * @author zhangweilin
 * @date 2017年12月25日 下午1:43:08
 *
 */
@CommonsLog
public class DecipherLongIdEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.isEmpty(text)) {
			setValue(text);
			return;
		} else if ("null".equals(text)) {
			setValue(null);
			return;
		}
		if (StringUtils.isNumber(text)) {
			try {
				setValue(Long.parseLong(text));
			} catch (Exception e) {
				e.printStackTrace();
				setValue(text);
				return;
			}
		} else {
			Set<String> keySet = (Set<String>) RequestContext.getRequest()
					.getAttribute(AbstractBusinessInterceptor.modelBasePackageName + "_ncryptKey");
			if (null == keySet) {
				throw new IllegalArgumentException("invalid argument: " + text);
			}
			System.out.println("keySet: "+keySet);
			keySet.stream().forEach(e -> {
				try {
					String idStr = AesUtil.aesDecodeWithBase64(e, text);
					if (StringUtils.isEmpty(idStr)) {
						return;
					}
					System.out.println("idStr: " + idStr);
					Long id = Long.parseLong(idStr);
					log.info("解析出来的【id】: " + id);
					setValue(id);
					return;
				} catch (Throwable e1) {
					e1.printStackTrace();
					setValue(text);

				}
			});
		}
	}

}
